package com.course.file.controller;

import com.course.file.config.FileUploadConfig;
import com.course.server.common.Result;
import com.course.server.dto.FileDto;
import com.course.server.enums.FileUseEnum;
import com.course.server.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * @author: Durian
 * @date: 2021/5/3 17:32
 */
@Slf4j
@RestController
public class UploadController {

    @Resource
    private FileUploadConfig fileUploadConfig;
    @Resource
    private FileService fileService;

    public static final String BUSINESS_NAME = "文件上传";

    @PostMapping("/upload")
    public Result upload(@RequestPart MultipartFile shard, FileDto fileDto) throws IOException {
        String key = fileDto.getKey();
        String suffix = fileDto.getSuffix();
        String name = fileDto.getName();
        String use = fileDto.getUse();
        Integer shardIndex = fileDto.getShardIndex();
        // 保存
        FileUseEnum fileUseEnum = FileUseEnum.get(use);
        // 文件夹不存在则创建
        String dir = fileUseEnum.name().toLowerCase();
        File directory = new File(fileUploadConfig.getLocation() + dir);
        if (!directory.exists()) {
            log.info("文件夹【{}】不存在，开始创建", fileUploadConfig.getLocation() + dir);
            boolean flag = directory.mkdirs();
            log.info("文件夹【{}】创建结果:{}", fileUploadConfig.getLocation() + dir, flag);
        }
        /*=========构建本地保存全路径=========*/
        // 拼接分片文件名
        String path = dir + File.separator + key + "." + suffix + "." + shardIndex;
        String fullPath = fileUploadConfig.getLocation() + path;
        shard.transferTo(new File(fullPath));
        log.info("文件【{}】保存到【{}】", name, fullPath);

        // 访问路径
        String imgPath = fileUploadConfig.getAccess() + path;
        fileDto.setPath(imgPath);
        fileService.save(fileDto);

        return Result.success(fileDto);
    }

    @GetMapping("/merge")
    public Result merge() {
        return Result.success();
    }
}
